package com.pureut.quality.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.quality.domain.QualityPatrolBadSample;
import com.pureut.quality.domain.QualityPatrolTemporary;
import com.pureut.quality.domain.dto.QualityPatrolBadSampleDto;
import com.pureut.quality.mapper.QualityPatrolBadSampleMapper;
import com.pureut.quality.mapper.QualityPatrolTemporaryMapper;
import com.pureut.quality.service.QualityPatrolBadSampleService;
import com.pureut.quality.service.QualityPatrolTemporaryService;
import com.pureut.system.api.domain.SysDictData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
 * 巡检不良样本表实现层
 * Author:C
 * Date:2023/02/13 11:36
 * @DESC
 */
@Service
public class QualityPatrolBadSampleServiceImpl extends ServiceImpl<QualityPatrolBadSampleMapper, QualityPatrolBadSample> implements QualityPatrolBadSampleService {

    @Resource
    QualityPatrolBadSampleMapper qualityPatrolBadSampleMapper;

    @Resource
    QualityPatrolTemporaryMapper qualityPatrolTemporaryMapper;

    @Resource
    QualityPatrolTemporaryService qualityPatrolTemporaryService;


    /**
     * 巡检不良样本列表
     *
     * @param patrolInspectionSheetNo
     * @return
     */
    @Override
    public List<QualityPatrolBadSampleDto> patrolBadSampleList(String patrolInspectionSheetNo) {

        //检验结果
        List<SysDictData> resultsArray = DictUtils.getDictCache("quality_inspection_results");
        Map<String, String> resultsMap = resultsArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<QualityPatrolBadSampleDto> patrolBadSampleList = qualityPatrolBadSampleMapper.getPatrolBadSampleList(patrolInspectionSheetNo);

        for (QualityPatrolBadSampleDto entity : patrolBadSampleList) {
            //检验结果
            entity.setInspectionResultsDict(resultsMap.get(entity.getInspectionResults()));
        }
        return patrolBadSampleList;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean getDeleteById(Long id) {
        QualityPatrolBadSample byId = getById(id);
        //修改物料状态
        QualityPatrolTemporary qualityPatrolTemporary = qualityPatrolTemporaryMapper.selectOne(new QueryWrapper<QualityPatrolTemporary>().lambda().eq(QualityPatrolTemporary::getMaterialNumber, byId.getSampleNumber()));

        qualityPatrolTemporary.setInspectionMark(2);
        boolean b = qualityPatrolTemporaryService.updateById(qualityPatrolTemporary);
        if (b) {
            qualityPatrolBadSampleMapper.deleteById(byId);
        }
        return b;
    }
}
